package com.dyc.controller;

import com.dyc.anno.Log;
import com.dyc.pojo.Dept;
import com.dyc.pojo.Result;
import com.dyc.service.DeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 接收请求,响应数据
 */
//@CrossOrigin(origins = "http://localhost:5173")
@RestController
public class DeptController {
    private static final Logger log = LoggerFactory.getLogger(DeptController.class);

    @Autowired
    private DeptService deptService;

    /**
     * 查询全部部门数据
     * @return
     */
    @GetMapping("/depts")
    public Result getDeptList() {
        //System.out.println("查询全部部门数据");
        log.info("查询全部部门数据");
        List<Dept> deptList = deptService.findAll();
        return Result.success(deptList);
    }

    /**
     * 前端传递的参数名和服务端的方法形参名保持一致
     * @param id
     * @return
     */
    @Log
    @DeleteMapping("/depts")
    public Result deleteDeptById(Integer id) {
        //System.out.println("根据id删除部门"+id);
        log.info("根据id删除部门{}",id);
        deptService.deleteById(id);
        return  Result.success();
    }

    /**
     * 新增部门
     * @param dept
     * @return
     */
    @Log
    @PostMapping("/depts")
    //@RequestBody将json格式转换为键值 dept中与json种名字一致
    public Result addDept(@RequestBody Dept dept) {
        log.info("新增部门{}",dept);
        deptService.addDept(dept);
        return Result.success();
    }

    /**
     * 根据id查询部门
     */
    @GetMapping("/depts/{id}")//参数一致
    public Result getInfo(@PathVariable Integer id) {
        log.info("根据id查询部门{}",id);
        Dept dept = deptService.searchDeptById(id);
        return Result.success(dept);
    }

    /**
     * 修改部门
     * @param dept
     * @return
     */
    @Log
    @PutMapping("/depts")
    public Result updateDept(@RequestBody Dept dept) {
        log.info("修改部门{}",dept);
        deptService.update(dept);
        return Result.success();
    }
}
